package com.ruoyi.function.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.function.constant.BusinessConstants;
import com.ruoyi.function.constant.ServiceTypeMapping;
import com.ruoyi.function.domain.bo.TechnicianBo;
import com.ruoyi.message.controller.NoticeController;
import com.ruoyi.message.notice.vo.NoticeVO;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.function.mapper.TechnicianMapper;
import com.ruoyi.function.domain.Technician;
import com.ruoyi.function.service.ITechnicianService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 技师Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-18
 */
@Service
public class TechnicianServiceImpl implements ITechnicianService 
{
    @Autowired
    private TechnicianMapper technicianMapper;
    @Autowired
    private  UserServiceImpl userService;
    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private NoticeController noticeController;

    /**
     * 查询技师
     * 
     * @param id 技师主键
     * @return 技师
     */
    @Override
    public Technician selectTechnicianById(Long id)
    {
        Technician technician = technicianMapper.selectTechnicianById(id);
        String s = ServiceTypeMapping.convertServiceIdsToChinese(technician.getServiceTypeIds());
        technician.setServiceTypeIds(s);
        BigDecimal bigDecimal = getTechnicianConfigValue(technician.getLevel().intValue());
        technician.setHourPrice(bigDecimal);
        return technician;
    }

    /**
     * 查询技师列表
     * 
     * @param technician 技师
     * @return 技师
     */
    @Override
    public List<Technician> selectTechnicianList(Technician technician)
    {
        return technicianMapper.selectTechnicianList(technician);
    }

    /**
     *
     * @param technicianBo 技师
     * @return
     */
    @Override
    public int insertTechnician(TechnicianBo technicianBo)
    {
        // 判断用户是否已经注册成为技师
        //获取当前用户id

        Long userId = SecurityUtils.getUserId();
        Technician technician1 = technicianMapper.selectByUserId(userId);
        if (StringUtils.isNotNull(technician1) && technician1.getAuditStatus()==2){
            throw new RuntimeException("你已经注册成为技师，请勿重复注册");
        }
        Technician technician = new Technician();
        BeanUtils.copyProperties(technicianBo,technician );
        if (technicianBo.getServiceAreasList() != null){
            technician.setServiceAreas(String.join(",", technicianBo.getServiceAreasList()));
        }
        if (technicianBo.getExperiencePhotosList() != null){
            technician.setExperiencePhotos(String.join(",", technicianBo.getExperiencePhotosList()));
        }
        if (technicianBo.getSkillCertificates() != null){
            technician.setSkillCertificate(String.join(",", technicianBo.getSkillCertificates()));
        }
        if (technicianBo.getServiceTypeIdsArray() != null){
            technician.setServiceTypeIds(String.join(",", technicianBo.getServiceTypeIdsArray()));
        }
        if (technicianBo.getPlatformCertificates() != null){
            technician.setPlatformCertificate(String.join(",", technicianBo.getPlatformCertificates()));
        }
        technician.setAuditStatus(BusinessConstants.dict.audit_status_1);
        technician.setUserId(userId);
        if (StringUtils.isNotNull(technician1) && technician1.getAuditStatus()!=2){
            return technicianMapper.updateTechnician(technician);
        }
        return technicianMapper.insertTechnician(technician);
    }

    /**
     * 修改技师
     * 
     * @param technician 技师
     * @return 结果
     */
    @Override
    public int updateTechnician(TechnicianBo technicianBo)
    {
        Technician technician = new Technician();
        BeanUtils.copyProperties(technicianBo,technician );
        if (technicianBo.getServiceAreasList() != null){
            technician.setServiceAreas(String.join(",", technicianBo.getServiceAreasList()));
        }
        if (technicianBo.getExperiencePhotosList() != null){
            technician.setExperiencePhotos(String.join(",", technicianBo.getExperiencePhotosList()));
        }
        if (technicianBo.getSkillCertificates() != null){
            technician.setSkillCertificate(String.join(",", technicianBo.getSkillCertificates()));
        }
        if (technicianBo.getPlatformCertificates() != null){
            technician.setPlatformCertificate(String.join(",", technicianBo.getPlatformCertificates()));
        }
        if (technicianBo.getServiceTypeIdsArray() != null){
            technician.setServiceTypeIds(String.join(",", technicianBo.getServiceTypeIdsArray()));
        }
        if (technicianBo.getLevel() != null){
            BigDecimal bigDecimal = getTechnicianConfigValue(technician.getLevel().intValue());
            technician.setHourPrice(bigDecimal);
        }

        technician.setAuditStatus(BusinessConstants.dict.audit_status_1);
        technician.setReceivingOrder(BusinessConstants.dict.receiving_order_0);

//        if (technician.getStatus()==BusinessConstants.dict.status_0 && technician.getReceivingOrder()!=BusinessConstants.dict.receiving_order_0){
//            technician.setReceivingOrder(BusinessConstants.dict.receiving_order_0);
//        }
        int i = technicianMapper.updateTechnician(technician);
        return i;
    }

    /**
     * 批量删除技师
     * 
     * @param ids 需要删除的技师主键
     * @return 结果
     */
    @Override
    public int deleteTechnicianByIds(Long[] ids)
    {
        return technicianMapper.deleteTechnicianByIds(ids);
    }

    /**
     * 删除技师信息
     * 
     * @param id 技师主键
     * @return 结果
     */
    @Override
    public int deleteTechnicianById(Long id)
    {
        return technicianMapper.deleteTechnicianById(id);
    }

    @Override
    @Transactional
    public int check(Technician technician) {
        Technician technician1 = technicianMapper.selectByUserId(technician.getUserId());
        //1:只有待审核状态可以修改
        if (BusinessConstants.dict.audit_status_1 !=technician1.getAuditStatus()) {
            //报错
            throw new RuntimeException("只有待审核状态可以审核");
        }
        String messageContent="";
        //同步修改用户
        Long userId = technician1.getUserId();
        SysUser userById = userService.getUserById(userId);
        if (BusinessConstants.dict.audit_status_2 == technician.getAuditStatus()){
            messageContent=BusinessConstants.message_7;


            SysUser user = new SysUser();
            user.setUserId(userId);
            //修改当前角色为技师
            user.setCurrentRole(2L);
            //修改拥有角色包含技师角色
            String roleTypes = userById.getRoleTypes();
            if (StringUtils.isNull(roleTypes)){
                user.setRoleTypes("2");
            }else if (roleTypes.indexOf("2") == -1){
                user.setRoleTypes(roleTypes+",2");
            }
            userService.updateUser(user);
        }else if (BusinessConstants.dict.audit_status_3 == technician.getAuditStatus()){
            //同步修改用户
            messageContent=BusinessConstants.message_8+technician.getAuditRemark();

        }
        // 获取等级对应的工时费用。
        BigDecimal bigDecimal = getTechnicianConfigValue(technician.getLevel().intValue());
        Technician technician2 = new Technician();
        technician2.setId(technician.getId());
        technician2.setAuditStatus(technician.getAuditStatus());
        technician2.setAuditRemark(technician.getAuditRemark());
        technician2.setHourPrice(bigDecimal);
        int i = technicianMapper.updateTechnician(technician2);
        if (StringUtils.isNull(technician.getLevel())){
            throw new RuntimeException("技师等级不能为空");
        }
        if (i <= 0){
            throw new RuntimeException("审批失败");
        }
        noticeController.sendMessage(technician.getUserId() + "", "2", messageContent);
        return i;
    }

    /**
     * 获取等级对应的工时费
     * @param level
     * @return
     */
    public BigDecimal getTechnicianConfigValue(Integer level) {
        // 1. 参数校验
        if (level == null) {
            throw new RuntimeException("技师等级不能为空");
        }

        // 2. 构建配置键
        final String configKey;
        if (level == 1) {
            configKey = "technician_level_1";
        } else if (level == 2) {
            configKey = "technician_level_2";
        } else if (level == 3) {
            configKey = "technician_level_3";
        } else {
            throw new RuntimeException("技师等级错误，当前等级：" + level);
        }

        // 3. 查询配置
        SysConfig config = configMapper.checkConfigKeyUnique(configKey);
        if (config == null || config.getConfigValue() == null) {
            throw new RuntimeException("未找到技师等级配置: " + configKey);
        }

        // 4. 转换配置值
        try {
            return new BigDecimal(config.getConfigValue().trim());
        } catch (NumberFormatException e) {
            throw new RuntimeException("配置值格式错误，配置项: " + configKey + "，值: " + config.getConfigValue(), e);
        }
    }
    @Override
    public int register(TechnicianBo technicianBo) {
        // 判断用户是否已经注册成为技师
        //获取当前用户id

        Long userId = SecurityUtils.getUserId();
        Technician technician1 = technicianMapper.selectByUserId(userId);
        if (StringUtils.isNotNull(technician1) && technician1.getAuditStatus()==2){
            throw new RuntimeException("你已经注册成为技师，请勿重复注册");
        }
        Technician technician = new Technician();
        BeanUtils.copyProperties(technicianBo,technician );
        if (technicianBo.getServiceAreasList() != null){
            technician.setServiceAreas(String.join(",", technicianBo.getServiceAreasList()));
        }
        if (technicianBo.getExperiencePhotosList() != null){
            technician.setExperiencePhotos(String.join(",", technicianBo.getExperiencePhotosList()));
        }
        if (technicianBo.getSkillCertificates() != null){
            technician.setSkillCertificate(String.join(",", technicianBo.getSkillCertificates()));
        }
        if (technicianBo.getServiceTypeIdsArray() != null){
            technician.setServiceTypeIds(String.join(",", technicianBo.getServiceTypeIdsArray()));
        }
        if (technicianBo.getPlatformCertificates() != null){
            technician.setPlatformCertificate(String.join(",", technicianBo.getPlatformCertificates()));
        }
        technician.setAuditStatus(BusinessConstants.dict.audit_status_1);
        technician.setUserId(userId);
        if (StringUtils.isNotNull(technician1) && technician1.getAuditStatus()!=2){
            technician.setId(technician1.getId());
            return technicianMapper.updateTechnician(technician);
        }
        return technicianMapper.insertTechnician(technician);
    }

    @Override
    public int receivingOrder(Integer receivingOorder) {
        Technician technician1 = technicianMapper.selectByUserId(SecurityUtils.getUserId());
       if ( technician1 == null){
           throw new RuntimeException("请先注册成为技师");
       }
        if  ( technician1.getAuditStatus() != 2){
            throw new RuntimeException("只有待审核状态可以修改接单状态");
        }
        Technician technician = new Technician();
        technician.setReceivingOrder(receivingOorder);
        technician.setUserId(SecurityUtils.getUserId());
        return technicianMapper.updateTechnicianByUserId(technician) ;
    }
}
